package com.anXin.article.service.impl;

import com.anXin.article.mapper.ArticlePublishMapper;
import com.anXin.article.mapper.SensitiveMapper;
import com.anXin.article.service.*;
import com.anXin.common.tess4j.Tess4jClient;
import com.anXin.model.article.dtos.ArticleDto;
import com.anXin.model.article.pojos.Article;
import com.anXin.model.article.pojos.ArticleChannel;
import com.anXin.model.article.pojos.Sensitive;
import com.anXin.model.common.dtos.ResponseResult;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.common.SensitiveWordUtil;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
@Transactional
public class ArticleAutoScanServiceImpl implements ArticleAutoScanService {

    @Lazy
    @Resource
    private ArticlePublishService articlePublishService;

    @Resource
    private ArticleService articleService;
    /**
     * 文章审核
     * @param id
     */
    @Async //标明该方法是一个异步方法
    public void autoScanArticle(Long id) {
        //查询文章
        Article article = articlePublishService.query().eq("id",id).one();
        if (article==null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }

        if (article.getStatus().equals(Article.Status.SUBMIT.getCode())){

            //自管理敏感词
            boolean isSensitive=handleSensitiveScan(article.getContent(),article);
            if (!isSensitive)return;
            //审核文本内容
            boolean isTextScan=handleTextScan(article.getContent(),article);
            if (!isTextScan)return;
            //审核图片
            List<String> images =new ArrayList<>();
            if (StringUtils.isNotBlank(article.getImages())){
                String[] split = article.getImages().split(",");
                images.addAll(Arrays.asList(split));
            }
            boolean isImagesScan=handleImagesScan(images,article);
            if (!isImagesScan)return;

            //审核成功
            ResponseResult responseResult = articleService.saveArticle(article);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("AutoScanServiceImpl-文章审核保存APP端失败!");
            }
            article.setId((Long) responseResult.getData());
            updateArticle(article,(short)9,"审核成功");
        }


    }

    @Resource
    private SensitiveMapper sensitiveMapper;

    /**
     * 自管理的敏感词审核
     * @param content
     * @param article
     * @return
     */
    public boolean handleSensitiveScan(String content, Article article) {
        boolean flag=true;
        //获取敏感词
        List<Sensitive> sensitives = sensitiveMapper.selectList(Wrappers.<Sensitive>lambdaQuery().select(Sensitive::getSensitives));
        List<String> sensitiveList = sensitives.stream().map(Sensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词
        SensitiveWordUtil.initMap(sensitiveList);

        //审核
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size()>0){
            updateArticle(article,(short) 2,"当前文章中存在违规内容"+map);
            flag=false;
        }
        return flag;
    }
    private void updateArticle(Article article, short status, String reason) {
        article.setStatus(status);
        article.setReason(reason);
        articlePublishService.updateById(article);
    }

    /**
     * 审核纯文本内容
     * @param content
     * @param article
     * @return
     */
    public boolean handleTextScan(String content, Article article) {
        if ((article.getTitle()+"-"+content).length()==0){
            return true;
        }
        return true;
    }

    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private Tess4jClient tess4jClient;
    /**
     * 审核图片
     * @param images
     * @param article
     * @return
     */
    private boolean handleImagesScan(List<String> images, Article article) {
        boolean flag=true;
        if (images==null||images.size()==0)return flag;
        images=images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList=new ArrayList<>();
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                BufferedImage read = ImageIO.read(in);
                String result = tess4jClient.doOCR(read);
                //过滤文字
                boolean isSensitive = handleSensitiveScan(result, article);
                if (!isSensitive){
                    return isSensitive;
                }
                imageList.add(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }


}
